/*
 * Copyright (C) 2011 The Android Open Source Project
 * Copyright (C) 2011 Jake Wharton
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.letv.android.client.view.title;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.letv.android.young.client.R;
import com.letv.android.client.view.BadgeView;
import com.letv.core.utils.UIsUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;

/**
 * This com.ledim.widget implements the dynamic action bar tab behavior that can change
 * across different configurations or circumstances.
 */
public class TabPageIndicator extends HorizontalScrollView implements PageIndicator {
    /** Title text used when no title is provided by the adapter. */
    private static final CharSequence EMPTY_TITLE = "";

    /**
     * Interface for a callback when the selected tab has been reselected.
     */
    public interface OnTabReselectedListener {
        /**
         * Callback when the selected tab has been reselected.
         * 
         * @param position
         * Position of the current center item.
         */
        void onTabReselected(int position);

        void dismissWindow();
    }

    // 单个字的长度默认为16，tab长度自定义时使用
//    protected static final int WOLD_DEFAULT_WIDTH = UIsUtils.dipToPx(16);
    protected static final int WOLD_DEFAULT_WIDTH = 16;
    // TAB的默认高度
//    protected static final int TAB_HEIGHT = UIsUtils.dipToPx(45);
    protected static final int TAB_HEIGHT = 45;
    protected final IcsLinearLayout mTabLayout;
    protected ViewPager mViewPager;
    protected int mSelectedTabIndex;
    protected Context mContext;
    protected OnTabReselectedListener mTabReselectedListener;
    protected ViewPager.OnPageChangeListener mListener;
    protected boolean mIsCustomTabWidth = false;
    private int mMaxTabWidth;
    private Runnable mTabSelector;

    private final OnClickListener mTabClickListener = new OnClickListener() {
        public void onClick(View view) {

            TabView tabView = (TabView) view;
            final int oldSelected = mViewPager.getCurrentItem();
            final int newSelected = tabView.getIndex();
            mViewPager.setCurrentItem(newSelected);
            if (oldSelected == newSelected && mTabReselectedListener != null) {
                mTabReselectedListener.onTabReselected(newSelected);
            }
        }
    };
    /**
     * 文字旁边的提醒View
     */
    private BadgeView mBadgeView;

    /**
     * 设置是否自动计算宽度，true:根据屏幕宽度计算；false，自定义宽度
     */
    private boolean autoWidth = false;

    /**
     * 屏幕宽度
     */
    private int screenWidth = 0;

    public TabPageIndicator(Context context) {
        this(context, null);
    }

    public TabPageIndicator(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        setHorizontalScrollBarEnabled(false);
        int w = UIsUtils.getScreenWidth(context);
        int h = UIsUtils.getScreenHeight(context);
        screenWidth = Math.min(w, h);

        mTabLayout = new IcsLinearLayout(context, R.attr.vpiTabPageIndicatorStyle);
        addView(mTabLayout, new LinearLayout.LayoutParams(WRAP_CONTENT, MATCH_PARENT));
        setBackgroundColor(getResources().getColor(R.color.letv_base_bg));
    }

    public void setOnTabReselectedListener(OnTabReselectedListener listener) {
        mTabReselectedListener = listener;
    }

    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        final boolean lockedExpanded = widthMode == MeasureSpec.EXACTLY;
        setFillViewport(lockedExpanded);
        final int childCount = mTabLayout.getChildCount();
        if (childCount > 1 && (widthMode == MeasureSpec.EXACTLY || widthMode == MeasureSpec.AT_MOST)) {
            if (childCount > 2) {
                mMaxTabWidth = (int) (MeasureSpec.getSize(widthMeasureSpec) * 0.4f);
            } else {
                mMaxTabWidth = MeasureSpec.getSize(widthMeasureSpec) / 2;
            }
        } else {
            mMaxTabWidth = -1;
        }

        final int oldWidth = getMeasuredWidth();
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        final int newWidth = getMeasuredWidth();

        if (lockedExpanded && oldWidth != newWidth) {
            setCurrentItem(mSelectedTabIndex);
        }
    }

    protected void animateToTab(final int position) {
        final View tabView = mTabLayout.getChildAt(position);
        if (mTabSelector != null) {
            removeCallbacks(mTabSelector);
        }
        mTabSelector = new Runnable() {
            public void run() {
                final int scrollPos = tabView.getLeft() - (getWidth() - tabView.getWidth()) / 2;
                smoothScrollTo(scrollPos, 0);
                mTabSelector = null;
            }
        };
        post(mTabSelector);
    }

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (mTabSelector != null) {
            post(mTabSelector);
        }
    }

    @Override
    public void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (mTabSelector != null) {
            removeCallbacks(mTabSelector);
        }
    }

    protected void addTab(int index, CharSequence text, int iconResId) {
        final TabView tabView = new TabView(getContext());
        tabView.mIndex = index;
        tabView.setFocusable(true);
        tabView.setOnClickListener(mTabClickListener);
        tabView.setText(text);

        if (iconResId != 0) {
            tabView.setCompoundDrawablesWithIntrinsicBounds(iconResId, 0, 0, 0);
        }

        // int tabWidth = autoWidth ? (screenWidth / mViewPager.getAdapter().getCount()) : UIsUtils.dipToPx(68);
        mTabLayout.addView(tabView, new LinearLayout.LayoutParams(WRAP_CONTENT, MATCH_PARENT, 1));
    }

    @Override
    public void onPageScrollStateChanged(int arg0) {
        if (mListener != null) {
            mListener.onPageScrollStateChanged(arg0);
        }
    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
        if (mListener != null) {
            mListener.onPageScrolled(arg0, arg1, arg2);
        }
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
//        if (mTabReselectedListener != null) {
//            mTabReselectedListener.dismissWindow();
//        }
    }

    @Override
    public void onPageSelected(int arg0) {
        setCurrentItem(arg0);
        if (mListener != null) {
            mListener.onPageSelected(arg0);
        }
    }

    @Override
    public void setViewPager(ViewPager view) {
        if (view == null) {
            removeAllViews();
            mViewPager = null;
        } else {
            if (mViewPager == view) {
                return;
            }
            if (mViewPager != null) {
                mViewPager.setOnPageChangeListener(null);
            }
            final PagerAdapter adapter = view.getAdapter();
            if (adapter == null) {
                throw new IllegalStateException("ViewPager does not have adapter instance.");
            }
            mViewPager = view;
            view.setOnPageChangeListener(this);
            notifyDataSetChanged();
        }
    }

    public void setViewPagerOnly(ViewPager view) {
        if (view == null) {
            mViewPager = null;
        } else {
            if (mViewPager == view) {
                return;
            }
            mViewPager = view;
            notifyDataSetChanged();
        }
    }

    /*
     * notifyDataSetChanged通知方法，表示为这个ViewPager提供View(一般是Fragment)的 Adapter
     * 里面的数据集发生变化时，执行的动作
     */
    public void notifyDataSetChanged() {
        mTabLayout.removeAllViews();
        PagerAdapter adapter = mViewPager.getAdapter();
        IconPagerAdapter iconAdapter = null;
        if (adapter instanceof IconPagerAdapter) {
            iconAdapter = (IconPagerAdapter) adapter;
        }
        final int count = adapter.getCount();
        for (int i = 0; i < count; i++) {
            CharSequence title = adapter.getPageTitle(i);
            if (title == null) {
                title = EMPTY_TITLE;
            }
            int iconResId = 0;
            if (iconAdapter != null) {
                iconResId = iconAdapter.getIconResId(i);
            }
            addTab(i, title, iconResId);
        }
        if (mSelectedTabIndex > count) {
            mSelectedTabIndex = count - 1;
        }
        setCurrentItem(mSelectedTabIndex);
        requestLayout();
    }

    @Override
    public void setViewPager(ViewPager view, int initialPosition) {
        setViewPager(view);
        setCurrentItem(initialPosition);
    }

    @SuppressWarnings("deprecation")
    @Override
    public void setCurrentItem(int item) {
        if (mViewPager == null) {
            throw new IllegalStateException("ViewPager has not been bound.");
        }
        mSelectedTabIndex = item;
        if (mSelectedTabIndex != item) {
            mViewPager.setCurrentItem(item);
        }

        final int tabCount = mTabLayout.getChildCount();
        for (int i = 0; i < tabCount; i++) {
            final View child = mTabLayout.getChildAt(i);
            final boolean isSelected = (i == item);
            child.setSelected(isSelected);
            if (isSelected) {
                animateToTab(item);
                ((TabView) child).setTextColor(mContext.getResources().getColor(R.color.letv_color_ff5895ed));
                child.setBackgroundResource(R.drawable.letv_tab_indicator_bg);
            } else {
                ((TabView) child).setTextColor(mContext.getResources().getColor(R.color.letv_color_ff444444));
                child.setBackgroundDrawable(null);
            }

            if (i == 0 && child instanceof FrameLayout) {
                ((FrameLayout) child).getChildAt(0).setBackgroundDrawable(null);
            }
        }
    }

    private void createBadgeView() {
        if (mBadgeView == null) {
            mBadgeView = new BadgeView(mContext, mTabLayout.getChildAt(0));
            mBadgeView.setText("");
            mBadgeView.setBackgroundResource(R.drawable.letv_vip_service_red_dot);
            mBadgeView.setTextSize(16);
        }
    }
    
    public void clear() {
        mSelectedTabIndex = -1;
    }

    /**
     * 服务到期---显示红色小点
     */
    public void setVipDotTagDisp() {
        createBadgeView();
        if (!mBadgeView.isShown()) {
            mBadgeView.show(false, null);
        }
    }

    /**
     * 服务到期---隐藏红色小点
     */
    public void setVipDotTagHide() {
        if (mBadgeView != null && mBadgeView.isShown()) {
            mBadgeView.hide(false, null);
        }
    }

    @Override
    public void setOnPageChangeListener(OnPageChangeListener listener) {
        mListener = listener;
    }

    public void setAutoWidth(boolean auto) {
        this.autoWidth = auto;
    }

    /**
     * 根据文字的长度确定tab的宽度
     * 
     * @param text
     * @return
     */
    protected int getTabWidth(CharSequence text) {
        if (TextUtils.isEmpty(text) || TextUtils.getTrimmedLength(text) == 0) {
            return 0;
        }
        // 判断汉字
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        int len = 0;
        for (int i =0; i<text.length();i++) {
            char cr = text.charAt(i);
            Matcher m = p.matcher(String.valueOf(cr));
            //非汉字时，长度为汉字的一半
           len += m.matches() ? WOLD_DEFAULT_WIDTH : WOLD_DEFAULT_WIDTH / 2;
        }
//        return len + UIsUtils.dipToPx(10);
        return len + 10;
    }

    protected class TabView extends TextView {
        private int mIndex;
        private CharSequence mText;
        // 没有指定时，根据文字长度计算出的宽度
        private int mCustomWidth = 0;
        // 没有指定时，默认的高度
        private int mCustomHeight = TAB_HEIGHT;
        // 指定的宽度
        private int mWidth = 0;
        // 指定的高度
        private int mHeight = TAB_HEIGHT;

        public TabView(Context context) {
            this(context, "");
        }

        @SuppressWarnings("deprecation")
        public TabView(Context context, CharSequence text) {
            super(context, null, R.attr.vpiTabPageIndicatorStyle);
            setGravity(Gravity.CENTER);
            setSingleLine();
            setTextAppearance(getContext(), R.style.TabPageIndicatorTextAppearance);
            setBackgroundDrawable(null);
            setText(text);
            mText = text;
        }

        @Override
        public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            if (mWidth != 0 && mHeight != 0) {
                setMeasuredDimension(mWidth, mHeight);
            } else if (mIsCustomTabWidth && !TextUtils.isEmpty(mText)) {
                mCustomWidth = getTabWidth(mText);
                mCustomHeight = TAB_HEIGHT;
                setMeasuredDimension(mCustomWidth, mCustomHeight);
            } else if (mMaxTabWidth > 0 && getMeasuredWidth() > mMaxTabWidth) {
                // Re-measure if we went beyond our maximum size.
                super.onMeasure(MeasureSpec.makeMeasureSpec(mMaxTabWidth, MeasureSpec.EXACTLY), heightMeasureSpec);
            }
        }

        /**
         * 指定tab的宽高
         * 
         * @param width
         * @param height
         */
        public void setSize(int width, int height) {
            mWidth = width;
            mHeight = height;
        }

        public int getIndex() {
            return mIndex;
        }

        public void setIndex(int index) {
            mIndex = index;
        }

        public int getCustomWidth() {
            return mCustomWidth;
        }

        public int getCustomHeight() {
            return mCustomHeight;
        }
    }
}
